package com.adam.springsecurity;

import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //响应状态403
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //返回格式
//        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
//        writer.write("{status: \"error\",\"msg\": \"权限不足，请联系管理员\"}");
        ClassPathResource classPathResource = new ClassPathResource("/templates/error403.html");
        BufferedReader reader = new BufferedReader(new InputStreamReader(classPathResource.getInputStream()));
        String str;
        while((str = reader.readLine()) != null) {
            writer.write(str);
        }
        writer.flush();
        writer.close();
    }
}
